package com.xyw.code.platform.common.entity.util;

import com.xyw.code.platform.common.entity.enums.MenuIsFrameEnum;
import com.xyw.code.platform.common.entity.po.SysDept;
import com.xyw.code.platform.common.entity.po.SysMenu;
import com.xyw.code.platform.common.entity.vo.DeptTreeVo;
import com.xyw.code.platform.common.entity.vo.MenuMetaVo;
import com.xyw.code.platform.common.entity.vo.MenuVo;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Classname PreUtil
 * @Description pre系统用户工具类
 * @Author 李号东 lihaodongmail@163.com
 * @Date 2019-04-27 16:52
 * @Version 1.0
 */
@UtilityClass
public class XUtil {

    /**
     * 不重复的验证码
     *
     * @param i
     * @return
     */
    public String codeGen(int i) {
        char[] codeSequence = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I',
                'O', 'P', 'L', 'K', 'J', 'H', 'G', 'F', 'D',
                'S', 'A', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '1',
                '2', '3', '4', '5', '6', '7', '8', '9', '0'};
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        int count = 0;
        while (true) {
            // 随机产生一个下标，通过下标取出字符数组中对应的字符
            char c = codeSequence[random.nextInt(codeSequence.length)];
            // 假设取出来的字符在动态字符中不存在，代表没有重复的
            if (stringBuilder.indexOf(c + "") == -1) {
                stringBuilder.append(c);
                count++;
                //控制随机生成的个数
                if (count == i) {
                    break;
                }
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 菜单是否存在
     * @param outMenus
     * @param menu
     * @return
     */
    public static boolean exists(List<SysMenu> outMenus, SysMenu menu) {
        boolean isExists = false;
        for(SysMenu m:outMenus){
            if(m.getId().equals(menu.getId())){
                isExists = true;
            }
        }
        return isExists;
    }

    /**
     * 根据需要的outMenus 去组装menus
     * @param outMenus
     * @param menus
     * @param menuType
     */
    public static void findMenuChild(List<SysMenu> outMenus, List<SysMenu> menus, Integer menuType) {
        outMenus.forEach(menu->{
            List<SysMenu> children = new ArrayList<>();
            menus.forEach(allMenu->{
                if(menu.getId().equals(allMenu.getParentId())){
                    allMenu.setParentName(menu.getName());
                    if(menu.getLevel()!=null){
                        allMenu.setLevel(menu.getLevel() + 1);
                    }
                    if (!exists(children, allMenu)) {
                        children.add(allMenu);
                    }
                }
                if(children.size()>0){
                    findMenuChild(children,menus,menuType);
                }
            });
            menu.setChildren(children);
        });
    }

    /**
     * 构建菜单组件
     * @param sysMenuList
     */
    public static  List<MenuVo> buildVueMenu(List<SysMenu> sysMenuList) {
        List<MenuVo> list = new LinkedList<>();
        sysMenuList.forEach(sysMenu -> {
                    if (sysMenu != null) {
                        List<SysMenu> menuDTOList = sysMenu.getChildren();
                        MenuVo menuVo = new MenuVo();
                        menuVo.setName(sysMenu.getName());
                        menuVo.setPath(sysMenu.getPath());
                        // 如果不是外链
                        if (sysMenu.getIsFrame()== MenuIsFrameEnum.IN.getType()) {
                            if (sysMenu.getParentId().equals("0")) {
                                //一级目录需要加斜杠，不然访问 会跳转404页面
                                menuVo.setPath("/" + sysMenu.getPath());
                                menuVo.setComponent(StringUtils.isEmpty(sysMenu.getComponent()) ? "Layout" : sysMenu.getComponent());
                            } else if (!StringUtils.isEmpty(sysMenu.getComponent())) {
                                menuVo.setComponent(sysMenu.getComponent());
                            }
                        }
                        menuVo.setMeta(new MenuMetaVo(sysMenu.getName(), sysMenu.getIcon()));
                        if (menuDTOList != null && menuDTOList.size() != 0 && sysMenu.getType() == 0) {
                            menuVo.setChildren(buildVueMenu(menuDTOList));
                            // 处理是一级菜单并且没有子菜单的情况
                        } else if (sysMenu.getParentId().equals("0")) {
                            menuVo.setAlwaysShow(false);
                            menuVo.setRedirect("noredirect");
                            MenuVo menuVo1 = new MenuVo();
                            menuVo1.setMeta(menuVo.getMeta());
                            // 非外链
                            if (sysMenu.getIsFrame() == MenuIsFrameEnum.IN.getType()) {
                                menuVo1.setPath("index");
                                menuVo1.setName(menuVo.getName());
                                menuVo1.setComponent(menuVo.getComponent());
                            } else {
                                menuVo1.setPath(sysMenu.getPath());
                            }
                            menuVo.setName(null);
                            menuVo.setMeta(null);
                            menuVo.setComponent("Layout");
                            List<MenuVo> list1 = new ArrayList<>();
                            list1.add(menuVo1);
                            menuVo.setChildren(list1);
                        }
                        list.add(menuVo);
                    }
                }
        );
        return list;
    }

    /**
     * 构建部门tree
     *
     * @param sysDepts
     * @param depts
     */
    public static void findChildren(List<SysDept> sysDepts, List<SysDept> depts) {
        for (SysDept sysDept : sysDepts) {
            List<SysDept> children = new ArrayList<>();
            for (SysDept dept : depts) {
                if (sysDept.getId() != null && sysDept.getId().equals(dept.getParentId())) {
                    dept.setParentName(sysDept.getName());
                    dept.setLevel(sysDept.getLevel() + 1);
                    children.add(dept);
                }
            }
            sysDept.setChildren(children);
            findChildren(children, depts);
        }
    }

    /**
     * 构建部门tree
     *
     * @param ids
     * @param menu
     */
    public List<String>  findChildrenIds(List<String> ids ,SysMenu menu) {
        List<SysMenu> childs = menu.getChildren();
        if(childs!=null){
            childs.forEach(child->{
                ids.add(child.getId());
                findChildrenIds(ids,child);
            });
        }
        return ids;
    }



    /**
     * 构建部门树
     * @param sysDepts
     * @param depts
     */
    public static void findChildrenDeptTree(List<DeptTreeVo> sysDepts, List<SysDept> depts) {
        for (DeptTreeVo sysDept : sysDepts) {
            sysDept.setId(sysDept.getId());
            sysDept.setLabel(sysDept.getLabel());
            List<DeptTreeVo> children = new ArrayList<>();
            for (SysDept dept : depts) {
                if (sysDept.getId().equals(dept.getParentId())) {
                    DeptTreeVo deptTreeVo1 = new DeptTreeVo();
                    deptTreeVo1.setLabel(dept.getName());
                    deptTreeVo1.setId(dept.getId());
                    children.add(deptTreeVo1);
                }
            }
            sysDept.setChildren(children);
            findChildrenDeptTree(children, depts);
        }
    }

    /**
     * 根据id集合  递归得到所有子id
     *
     */
    public static List<String> getChildsId(List<String> childIds , Map<String,List<String>> map ,String id) {
        if(childIds==null){
            childIds = new ArrayList<>();
        }
        List<String> ids = map.get(id);
        if(ids!=null){
            childIds.addAll(ids);
            for(String oneId:ids){
                getChildsId(childIds,map,oneId);
            }
        }
        return childIds;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param rawPass
     * @return
     */
    public String encode(String rawPass) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(rawPass);
    }


    /**
     * 校验密码
     *
     * @param newPass
     * @param passwordEncoderOldPass
     * @return
     */
    public boolean validatePass(String newPass, String passwordEncoderOldPass) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(newPass, passwordEncoderOldPass);
    }



    /**
     * 得到字符串str里面第一个满足regex正则表达式的字符串
     *
     * @param str
     * @param regex
     * @return
     */
    public String getRegex(String str, String regex) {
        Pattern p = Pattern.compile(regex);
        Matcher matcher = p.matcher(str);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    /**
     * 如果根据parentId得到父级是不是为空
     *
     * @param parentId
     * @return
     */
    public Boolean parentIsNull(String parentId) {
       if(StringUtils.isBlank(parentId)||"0".equals(parentId)){
           return true;
       }
       return false;
    }


}
